const winston = require('winston')
const mongoose = require('mongoose')

const _conf = require('../../configs/configure')

const mongo_url = 'mongodb://' + _conf.mongodb.address + ':' + _conf.mongodb.port

const listenHTTP = app => {
  var server = app.listen(_conf.port, () => {
    var host = server.address().address
    var port = server.address().port
    winston.info('Backend started at http://%s:%s', host, port)
  })
}

const initMongoose = () => {
  const connect = () => {
    mongoose.Promise = global.Promise
    mongoose.connect(
      mongo_url + '/' + _conf.mongodb.database,
      {
        keepAlive: true,
        useNewUrlParser: true,
        useUnifiedTopology: true
      },
      (e) => {
        let dbStatus = ''
        if (e) {
          dbStatus = `*    Error connecting to DB: ${err}`
        }
        dbStatus = `*    DB Connection: OK`
        if (process.env.NODE_ENV !== 'test') {
          // Prints initialization
          console.log('****************************')
          console.log('*    Starting Server')
          console.log(`*    Port: ${process.env.PORT || 3000}`)
          console.log(`*    NODE_ENV: ${process.env.NODE_ENV}`)
          console.log(`*    Database: MongoDB`)
          console.log(dbStatus)
          console.log(`****************************\n`)
        }
      }
    )
    mongoose.set('useCreateIndex', true)
    mongoose.set('useFindAndModify', false)
  }
  connect()
  mongoose.connection.on('error', console.log)
  mongoose.connection.on('disconnected', connect)
}

module.exports = {
  listenHTTP,
  initMongoose
}
